Consider the following three things I’ve said to my toddler:
Unlike my toddler, the computer does listen, but my toddler has more common sense!
Remember that operators like <= and == also produce True/False answers:
There is a second set of logical operators that apply in very specific circumstances. These are called ‘bitwise’ operators and apply to data specified in bits.
| Regular Operator | Bitwise Equivalent |
|---|---|
and |
& |
or |
| |
not |
~ |
Let’s see (briefly) how these work…
This gives us that x is '100110' and y is '11', so now:
| Operator | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| x | 1 | 0 | 0 | 1 | 1 | 0 |
| y | 0 | 0 | 0 | 0 | 1 | 1 |
| x & y | 0 | 0 | 0 | 0 | 1 | 0 |
| x | y | 1 | 0 | 0 | 1 | 1 | 1 |
| ~y | 1 | 1 | 1 | 1 | 0 | 0 |
| x & ~y | 1 | 0 | 0 | 1 | 0 | 0 |
Bitwise operations are very, very fast and so are a good way to, say, find things in large data sets. You’ve been warned.
Beware of using logic with things that are not what they appear:
None is Python’s way of saying that something has no value at all (not 0 or ""… but None). It is a class.numpy package to deal with things like -ve and +ve infinity and similar ‘issues’.np.nan should be used whenever you are dealing with data (e.g. see Pandas!).
Critically:
We’ve touched on these before:
g = ['Harvey','Rose','Batty','Jefferson']
if 'Batty' in g:
print("In the group!")
if 'Marx' not in g:
print("Not in the group!")The set data type also supports in, and not in together with all of the set maths (union, intersect, etc.).
Membership maths:
Logic • Jon Reades